package com.dzt.btserial;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.adayo.btsppsdk.constant.HudConnectStatus;
import com.adayo.btsppsdk.utils.JLogKit;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MainActivity extends AppCompatActivity implements Contract.View,
		View.OnClickListener,
		AdapterView.OnItemClickListener {

	public static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
	public static final UUID CONNECT_UUID = UUID.fromString(SPP_UUID);
	private static final int LIST_CHANGE = 1;
	private static final int SEARCH_CHANGE = 2;
	private static final int SPP_STATUS_CHANGE = 3;
	private BtListAdapter adapter;
	private ListView listView;
	private Button btnStartService;
	private Button btnStartSearch;
	private Button btnDisconnect;
	private TextView tvStatus;
	private List<BluetoothDevice> devices = new ArrayList<>();
	private AcceptThread acceptThread;
	private HudConnectStatus connectState = HudConnectStatus.CONNECT_STATE_IDLE;
	private BtSppPresenter presenter;


	private Handler handler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message message) {
			switch (message.what) {
				case LIST_CHANGE:
					adapter.notifyDataSetChanged();
					break;
				case SEARCH_CHANGE:
					btnStartSearch.setText("开始搜索");
					break;
				case SPP_STATUS_CHANGE:
					tvStatus.setText("" + connectState);
					if (connectState == HudConnectStatus.CONNECT_STATE_CONNECTED) {
						btnDisconnect.setVisibility(View.VISIBLE);
					} else {
						btnDisconnect.setVisibility(View.GONE);
					}
					break;
				default:
					break;
			}
			return true;
		}
	});

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initWidgets();
		presenter = new BtSppPresenter(this);
		adapter = new BtListAdapter(this, devices);
		listView.setAdapter(adapter);
	}

	private void initWidgets() {
		btnStartSearch = (Button) findViewById(R.id.btn_start_search);
		btnStartSearch.setOnClickListener(this);
		btnStartService = (Button) findViewById(R.id.btn_start_service);
		btnStartService.setOnClickListener(this);
		btnDisconnect = (Button) findViewById(R.id.btn_disconnect);
		btnDisconnect.setOnClickListener(this);
		tvStatus = (TextView) findViewById(R.id.tv_status);
		listView = (ListView) findViewById(R.id.lv_bluetooth);
		listView.setOnItemClickListener(this);
		handler.sendEmptyMessage(SPP_STATUS_CHANGE);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		stopService();
		presenter.onDestroy();
	}

	@Override
	public void onFoundNewDevice(BluetoothDevice device) {
		devices.add(device);
		handler.sendEmptyMessage(LIST_CHANGE);
	}

	@Override
	public void onSearchFinish() {
		connectChangeBroadcast(HudConnectStatus.CONNECT_STATE_SEARCHED);
		handler.sendEmptyMessage(SEARCH_CHANGE);
	}

	@Override
	public void onBonded(BluetoothDevice device) {
		handler.sendEmptyMessage(LIST_CHANGE);
	}

	@Override
	public void onSwitchStateChange(int state) {
		if (state == BluetoothAdapter.STATE_ON) {
			connectChangeBroadcast(HudConnectStatus.CONNECT_STATE_IDLE);
		} else if (state == BluetoothAdapter.STATE_OFF) {
			connectChangeBroadcast(HudConnectStatus.CONNECT_STATE_BT_NOT_OPEN);
		}
	}

	@Override
	public void onSppDisconnected() {
		connectChangeBroadcast(HudConnectStatus.CONNECT_STATE_IDLE);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.btn_start_service:
				if (acceptThread == null) {
					btnStartService.setText("关闭服务");
					startService();
					listView.setVisibility(View.GONE);
				} else {
					btnStartService.setText("开启服务");
					stopService();
					listView.setVisibility(View.VISIBLE);
				}
				break;
			case R.id.btn_start_search:
				if (presenter.isDiscovering()) {
					btnStartSearch.setText("开始搜索");
					presenter.onCancelDiscovery();
				} else {
					btnStartSearch.setText("停止搜索");
					devices.clear();
					handler.sendEmptyMessage(LIST_CHANGE);
					connectChangeBroadcast(HudConnectStatus.CONNECT_STATE_SEARCHING);
					presenter.onStartDiscovery();
					listView.setVisibility(View.VISIBLE);
				}
				break;
			case R.id.btn_disconnect:
				presenter.onDisconnect();
				break;
			default:
				break;
		}
	}

	private void startService() {
		if (acceptThread == null) {
			acceptThread = new AcceptThread();
			acceptThread.start();
		}
	}

	private void stopService() {
		if (acceptThread != null) {
			acceptThread.close();
			acceptThread = null;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
		BluetoothDevice device = devices.get(i);
		presenter.onCancelDiscovery();
		connectChangeBroadcast(HudConnectStatus.CONNECT_STATE_CONNECTING);
		if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
			presenter.onConnect(device);
		} else {
			presenter.onPairDevice(device);
		}
	}

	private void connectChangeBroadcast(HudConnectStatus state) {
		JLogKit.getInstance().e("connectChangeBroadcast state = " + state);
		connectState = state;
		handler.sendEmptyMessage(SPP_STATUS_CHANGE);
	}

	@Override
	public void onBTStatusChange(HudConnectStatus status) {
		connectChangeBroadcast(status);
	}

	//服务端蓝牙
	private class AcceptThread extends Thread {
		private BluetoothServerSocket serverSocket;
		private BluetoothSocket socket;
		private InputStream is;
		private OutputStream os;
		private boolean isRunning = false;

		public AcceptThread() {
			//创建BluetoothServerSocket对象
			try {
				serverSocket = presenter.getBluetoothAdapter().listenUsingInsecureRfcommWithServiceRecord("name",
						CONNECT_UUID);
			} catch (IOException e) {
				e.printStackTrace();
			}
			isRunning = true;
		}

		@Override
		public void run() {
			//等待接受蓝牙客户端的请求
			try {
				socket = serverSocket.accept();
				is = socket.getInputStream();
				os = socket.getOutputStream();
				while (isRunning) {
					byte[] buffer = new byte[128];
					int count = is.read(buffer);
					Message message = new Message();
					message.obj = new String(buffer, 0, count, "utf-8");
					handler.sendMessage(message);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void close() {
			isRunning = false;
			this.interrupt();
			try {
				if(socket != null){
					socket.close();
					socket = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
